<template>
  <div class="idle_main">
    <!--    顶部导航条-->
    <navheader></navheader>
<!--    主体内容-->
    <div class="chat-container flex flex-pack-justify">
<!--      侧标聊天用户-->
      <div class="chat-user">
        <div class="chat-user-item flex flex-algin-center flex-pack-justify" :class="{'active':item.active}" v-for="(item,index) in chatUserList" @click="chatTap(index,item.user_id)">
          <div class="flex flex-algin-center">
            <img :src="img.testimg"><p>{{item.nickname}}</p>
            <span class="newMsg pl-4" v-if="item.hasNewMsg">新消息</span>
          </div>
        </div>
      </div>
<!--     右边聊天窗 -->
      <div class="chat-main flex-1 flex flex-v">
        <div class="chat-user-base flex flex-algin-center" v-if="currentChatUser">
          <img :src="img.testimg">
          <p>{{currentChatUser.nickname}}</p>
        </div>
<!--        聊天记录-->
        <div class="chat-main-panel flex-1">
          <div v-if="currentChatMsg.length>0">
            <div class="chat-msg-item flex" v-for="chat in currentChatMsg" :class="[current_user_id==chat.from_user_id ?'sender':'receive']">
              <img :src="img.testimg" class="headimg">
              <div class="chat-msg flex flex-v">
                <div class="chat-msg-base flex">
                  <label>{{chat.from_user_nickname}}</label>
                  <p>{{chat.datetime}}</p>
                </div>
                <div class="chat-msg-info">{{chat.msg}}</div>
              </div>
            </div>
          </div>
          <div v-else>
            <div class="no-chat-msg">~没有消息</div>
          </div>
        </div>
<!--        输入框-->
        <div class="chat-send-msg flex">
          <label style="font-size: 16px" class="pt-2">聊天消息：</label>
          <el-input placeholder="请输入..." v-model="inputMsg" style="width: 800px"></el-input>
          <el-button class="sendBtn ml-4" @click="sendMsg" type="primary">发送消息</el-button>
        </div>
      </div>
    </div>
    <!--    底部导航条-->
    <myfooter></myfooter>
  </div>
</template>

<script>
import myfooter from "@/components/myfooter";
import navheader from "@/components/navheader";
import testimg from '@/assets/test/3.jpg';
import {getNowUserIdByToken} from '@/api/User'


export default {
  name: "idle_talks",
  components:{
    myfooter,
    navheader
  },
  data(){
    return{
      img:{
        testimg,
      },
      inputMsg:"",
      ws:null,
      chatUserList:[
        {user_id:1,nickname:"用户一",active:false,hasNewMsg:false},
        {user_id:12,nickname:"用户十二",active:false,hasNewMsg:false},
        {user_id:3,nickname:"用户三",active:false,hasNewMsg:false},
      ],
      // 当前用户是谁，当前登录的用户
      currentUser:null,
      current_user_id:0,
      current_user_name:'',
      current_user_img:'',

      //当前聊天消息
      currentChatMsg:[],

      // 跟谁聊天
      currentChatUser:null,
      currentChatUserIndex:0,
      chatMsgList:[],

      // 初始化聊天消息，聊天消息格式
      chatMsg:[
        {from_user_id:1,from_user_nickname:"用户一",to_user_id:12,msg:"在吗，找你商量个事",datetime:"2021-05-14 12:15:20"},
        {from_user_id:12,from_user_nickname:"用户十二",to_user_id:1,msg:"在的呀。",datetime:"2021-05-15 01:25:06"},
        {from_user_id:12,from_user_nickname:"用户十二",to_user_id:1,msg:"微信上找我吧",datetime:"2021-05-15 01:25:06"},
        {from_user_id:1,from_user_nickname:"用户一",to_user_id:12,msg:"我没相中你，上次吃饭的钱转我一半吧！",datetime:"2021-05-14 12:15:20"},
      ],



    }
  },
  watch:{
    currentChatUserIndex: {
      handler(newVal,oldVal) {
        this.currentChatMsg = this.chatMsgList[newVal];

        setTimeout(() => {
          $(".chat-main-panel").scrollTop(500000);
        }, 0);
      },
      immediate: true
    },
    chatMsgList:{
      handler(newVal, oldVal) {
        this.currentChatMsg = this.chatMsgList[this.currentChatUserIndex];
        setTimeout(()=>{
          $(".chat-main-panel").scrollTop(500000);
        },0);
      },
      immediate: true
    },
  },
  created(){
    let _this=this;
    //
    // _this.link_test();
    getNowUserIdByToken({

    }).then(res => {
      //console.log(res.data);
      this.current_user_id=res.data.user_id;
      this.current_user_name=res.data.user_name;
      this.current_user_img=res.data.user_img;

      // 初始化聊天记录，模拟缓存
      this.chatMsgList = (new Array(this.chatUserList.length)).fill([]);

      // 默认跟第一个聊天
      this.chatUserList = this.chatUserList.filter(item=>item.user_id!= this.current_user_id);

      this.chatUserList[0].active = true;
      this.currentChatUser = this.chatUserList[0];

      this.ws = new WebSocket("ws://www.caihuay.com.cn:2348");

      this.ws.onopen = function() {

        console.log("连接成功");

        _this.ws.send(JSON.stringify({type:"bind",uid: _this.current_user_id}));

      };

      this.ws.oncolse = function(){
        console.log("close。。。。。。。")
      };

      this.ws.onmessage = function(e) {

        console.log("收到服务端的消息：" + e.data);
        let data = JSON.parse(e.data);

        // 表示聊天 一对一聊天
        if(data.type == "text"){

          // 当前聊天窗口的这个跟发送消息的这个是一个人
          if(_this.currentChatUser.user_id == data.from_user_id){
            _this.chatMsgList[_this.currentChatUserIndex].length>0?
                _this.chatMsgList[_this.currentChatUserIndex].push(data):
                _this.$set(_this.chatMsgList,_this.currentChatUserIndex,new Array(1).fill(data));
          }
        }

        // 消息通知
        if(data.type == "message"){
          console.log(data.message);
        }

      };



    });


  },
  methods:{
    // link_test(){
    //   let ws= new WebSocket("ws://www.caihuay.com.cn:2348");
    //   ws.onopen =function (){
    //     console.log("连接成功！！");
    //     ws.send("tom");
    //
    //   };
    //
    //   ws.onmessage=function (e){
    //     console.log("收到服务器的消息"+e.data);
    //
    //   }
    // },
    //切换用户
    chatTap(index,user_id){
      this.chatUserList.forEach(item=>{
        item.active = item.user_id === user_id?true:false;
      });
      this.currentChatUser = this.chatUserList.filter(item=>item.user_id===user_id)[0];
      this.currentChatUserIndex = index;
      this.currentChatUser.hasNewMsg = false;
    },
    //发送消息
    sendMsg(){
      if($.trim(this.inputMsg).length==0) return false;
      let date = new Date();
      let curretnTime = date.getFullYear()+"-"+date.getMonth()+1+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes();

      let msg = {
        type:"text",
        from_user_id:this.current_user_id,
        from_user_nickname:this.current_user_name,
        to_user_id:this.currentChatUser.user_id,
        msg:this.inputMsg,
        datetime:curretnTime,
      };

      this.chatMsgList[this.currentChatUserIndex].length>0?
          this.chatMsgList[this.currentChatUserIndex].push(msg):
          this.$set(this.chatMsgList,this.currentChatUserIndex,new Array(1).fill(msg));

      // 清空
      this.inputMsg = "";
      $(".input-txt").focus();

      this.ws.send(JSON.stringify(msg));
    }


  },

}
</script>

<style scoped>
.idle_main{
  background: url('~@/assets/discussion/back.jpg') no-repeat center;
  background-size:cover;
  width: 100%;
  background-attachment:fixed;
}

</style>
